package org.jeecg.modules.engineering.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.engineering.entity.EquipInfo;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.engineering.entity.EquipCollectTrigger;
import org.jeecg.modules.engineering.entity.EquipCollectItemDetail;
import org.jeecg.modules.engineering.vo.EquipCollectItemDetailPage;
import org.jeecg.modules.engineering.service.IEquipCollectItemDetailService;
import org.jeecg.modules.engineering.service.IEquipCollectTriggerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 每个小区的采集项
 * @Author: jeecg-boot
 * @Date:   2019-09-12
 * @Version: V1.0
 */
@RestController
@RequestMapping("/b/engineering/equipCollectItemDetail")
@Slf4j
public class EquipCollectItemDetailController {
	@Autowired
	private IEquipCollectItemDetailService equipCollectItemDetailService;
	@Autowired
	private IEquipCollectTriggerService equipCollectTriggerService;

	 @Autowired
	 private ISysUserRoleService sysUserRoleService;

	/**
	  * 分页列表查询
	 * @param equipCollectItemDetail
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "小区级别的采集项-分页列表查询")
	@ApiOperation(value="小区级别的采集项-分页列表查询", notes="小区级别的采集项-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<EquipCollectItemDetail>> queryPageList(EquipCollectItemDetail equipCollectItemDetail,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		//权限处理
		List<String> projectIds = sysUserRoleService.queryProjectIds(equipCollectItemDetail);
		equipCollectItemDetail.resetValue();
		Result<IPage<EquipCollectItemDetail>> result = new Result<IPage<EquipCollectItemDetail>>();
		QueryWrapper<EquipCollectItemDetail> queryWrapper = QueryGenerator.initQueryWrapper(equipCollectItemDetail, req.getParameterMap());
		if (projectIds.size() <=0){
			queryWrapper.eq("project_id","");
		}else{
			queryWrapper.in("project_id",projectIds);
		}
		Page<EquipCollectItemDetail> page = new Page<EquipCollectItemDetail>(pageNo, pageSize);
		IPage<EquipCollectItemDetail> pageList = equipCollectItemDetailService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	 /**
	  * 根据小区查询采集项列表
	  * @return
	  */
	 @AutoLog(value = "小区级别的采集项-根据小区查询采集项列表")
	 @ApiOperation(value="小区级别的采集项-根据小区查询采集项列表", notes="小区级别的采集项-根据小区查询采集项列表")
	 @GetMapping(value = "/queryListByProjectId")
	 public Result<List<EquipCollectItemDetail>> queryListByProjectId(@RequestParam(name="projectId") String projectId) {
		 List<EquipCollectItemDetail> list = equipCollectItemDetailService.queryListByProjectId(projectId);
		 return Result.ok(list);
	 }

	/**
	  *   添加
	 * @param equipCollectItemDetailPage
	 * @return
	 */
	@AutoLog(value = "小区级别的采集项-添加")
	@ApiOperation(value="小区级别的采集项-添加", notes="小区级别的采集项-添加")
	@PostMapping(value = "/add")
	public Result<EquipCollectItemDetail> add(@RequestBody EquipCollectItemDetailPage equipCollectItemDetailPage) {
		Result<EquipCollectItemDetail> result = new Result<EquipCollectItemDetail>();
		try {
			EquipCollectItemDetail equipCollectItemDetail = new EquipCollectItemDetail();
			BeanUtils.copyProperties(equipCollectItemDetailPage, equipCollectItemDetail);
			
			equipCollectItemDetailService.saveMain(equipCollectItemDetail, equipCollectItemDetailPage.getEquipCollectTriggerList());
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param equipCollectItemDetailPage
	 * @return
	 */
	@AutoLog(value = "小区级别的采集项-编辑")
	@ApiOperation(value="小区级别的采集项-编辑", notes="小区级别的采集项-编辑")
	@PutMapping(value = "/edit")
	public Result<EquipCollectItemDetail> edit(@RequestBody EquipCollectItemDetailPage equipCollectItemDetailPage) {
		Result<EquipCollectItemDetail> result = new Result<EquipCollectItemDetail>();
		EquipCollectItemDetail equipCollectItemDetail = new EquipCollectItemDetail();
		BeanUtils.copyProperties(equipCollectItemDetailPage, equipCollectItemDetail);
		EquipCollectItemDetail equipCollectItemDetailEntity = equipCollectItemDetailService.getById(equipCollectItemDetail.getId());
		if(equipCollectItemDetailEntity==null) {
			result.error500("未找到对应实体");
		}else {
			//boolean ok = equipCollectItemDetailService.updateById(equipCollectItemDetail);
			equipCollectItemDetailService.updateMain(equipCollectItemDetail, equipCollectItemDetailPage.getEquipCollectTriggerList());
			result.success("修改成功!");
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "小区级别的采集项-删除")
	@ApiOperation(value="小区级别的采集项-删除", notes="小区级别的采集项-删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try {
			equipCollectItemDetailService.delMain(id);
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "小区级别的采集项-批量删除")
	@ApiOperation(value="小区级别的采集项-批量删除", notes="小区级别的采集项-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<EquipCollectItemDetail> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<EquipCollectItemDetail> result = new Result<EquipCollectItemDetail>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.equipCollectItemDetailService.delBatchMain(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "小区级别采集项-通过id查询")
	@ApiOperation(value="小区级别采集项-通过id查询", notes="小区级别采集项-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<EquipCollectItemDetail> queryById(@RequestParam(name="id",required=true) String id) {
		Result<EquipCollectItemDetail> result = new Result<EquipCollectItemDetail>();
		EquipCollectItemDetail equipCollectItemDetail = equipCollectItemDetailService.getById(id);
		if(equipCollectItemDetail==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(equipCollectItemDetail);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "小区级别采集项-通过id查询")
	@ApiOperation(value="小区级别采集项-通过id查询", notes="小区级别采集项-通过id查询")
	@GetMapping(value = "/queryEquipCollectTriggerByMainId")
	public Result<List<EquipCollectTrigger>> queryEquipCollectTriggerListByMainId(@RequestParam(name="id",required=true) String id) {
		Result<List<EquipCollectTrigger>> result = new Result<List<EquipCollectTrigger>>();
		List<EquipCollectTrigger> equipCollectTriggerList = equipCollectTriggerService.selectByMainId(id);
		result.setResult(equipCollectTriggerList);
		result.setSuccess(true);
		return result;
	}

	 @GetMapping(value = "/checkHave")
	 public Result<String> checkHave(String projectId,String itemId,String id) {
		 boolean isHave = equipCollectItemDetailService.checkHave(projectId,itemId,id);
		 if(isHave){
			 return Result.error("当前小区下该采集项已配置");
		 }
		 return Result.ok("success");
	 }

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<EquipCollectItemDetail> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              EquipCollectItemDetail equipCollectItemDetail = JSON.parseObject(deString, EquipCollectItemDetail.class);
              queryWrapper = QueryGenerator.initQueryWrapper(equipCollectItemDetail, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<EquipCollectItemDetailPage> pageList = new ArrayList<EquipCollectItemDetailPage>();
      List<EquipCollectItemDetail> equipCollectItemDetailList = equipCollectItemDetailService.list(queryWrapper);
      for (EquipCollectItemDetail equipCollectItemDetail : equipCollectItemDetailList) {
          EquipCollectItemDetailPage vo = new EquipCollectItemDetailPage();
          BeanUtils.copyProperties(equipCollectItemDetail, vo);
          List<EquipCollectTrigger> equipCollectTriggerList = equipCollectTriggerService.selectByMainId(equipCollectItemDetail.getId());
          vo.setEquipCollectTriggerList(equipCollectTriggerList);
          pageList.add(vo);
      }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "每个小区的采集项列表");
      mv.addObject(NormalExcelConstants.CLASS, EquipCollectItemDetailPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("每个小区的采集项列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<EquipCollectItemDetailPage> list = ExcelImportUtil.importExcel(file.getInputStream(), EquipCollectItemDetailPage.class, params);
              for (EquipCollectItemDetailPage page : list) {
                  EquipCollectItemDetail po = new EquipCollectItemDetail();
                  BeanUtils.copyProperties(page, po);
                  equipCollectItemDetailService.saveMain(po, page.getEquipCollectTriggerList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
